/*
 * Copyright (c) 2018-2023 北京华恒盛世科技有限公司
 * QUICKPOOL is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
*/

#include "subcmd.h"

static void migratejob_usage(const char *);

/**
 * @brief       qp job mig handler, to migrate job from one node to another.
 *
 * @param[in]   argc          #1: number of input argument
 * @param[in]   argv          #2: string array of the input argument
 *
 * @retval      0             #1: succeed
 * @retval      1             #2: input option is wrong or kind of input argument not specified
 * @retval      2             #3: argument has syntax error
 * @retval      3             #4: failed to migrate the job
 * @retval      4             #5: not enough memory
 */
int
cmd_migrate_job(int argc, char **argv)
{
    char *strUser=NULL, *strJobName=NULL, *strSpecNode=NULL;
    while (TRUE) {
        int option_index = 0;
        static struct option long_options[] = {
            {"help", no_argument, 0, 'h'},
            {"node", required_argument, 0, 'm'},
            {"user", required_argument, 0, 'u'},
            {"jobname", required_argument, 0, 'J'},
            {NULL, 0, 0, 0}
        };

        int opt;
        opt = getopt_long(argc, argv, "hm:u:J:", long_options, &option_index);
        if (-1 == opt) {
            break;
        }

        switch (opt) {
        case 'm':
            if (NULL != strSpecNode) {
                fprintf(stderr, "Do not specify -m/--node option for multiple times.\n");
                migratejob_usage(argv[0]);
                exit(1);
            }

            strSpecNode = optarg;

	    break;
        case 'u':
            if (NULL != strUser) {
                fprintf(stderr, "Do not specify -u/--user option for multiple times.\n");
                migratejob_usage(argv[0]);
                exit(1);
            }

            if (0 >= strlen(optarg)) {
                fprintf(stderr, "Specify a user name with -u/--user option.\n");
                migratejob_usage(argv[0]);
                exit(1);
            }

            strUser = optarg;

            break;
        case 'J':
            if (0 < strlen(optarg)) {
                fprintf(stderr, "Specify a job name with -J/--jobname option.\n");
                migratejob_usage(argv[0]);
                exit(1);
            }

            strJobName = optarg;

            break;
        case 'h':
            migratejob_usage(argv[0]);
            exit(0);
        case '?':
        default:
            migratejob_usage(argv[0]);
            exit(1);
        }
    }

    struct request migrateRequest;
    memset(&migrateRequest, 0, sizeof(struct request));

    int numJobIds;
    JOBID_T *jobIds = NULL;
    numJobIds = get_jobids_fromargv(argc, argv, &jobIds);
    if (0 < numJobIds) { // specified job id, ignore -J and -u options.

        migrateRequest.number = 1;
        migrateRequest.keyvalues = (struct keyvalue *)calloc(2, sizeof(struct keyvalue));
        if (NULL == migrateRequest.keyvalues) {
            fprintf(stderr, "calloc(%ld) failed due to %m.\n",
                    2*sizeof(struct keyvalue));
            exit(4);
        }

        unsigned int size = numJobIds*sizeof(JOBID_T) + 10;
        migrateRequest.keyvalues[0].key = REQUEST_KEY_JOBIDS;
        migrateRequest.keyvalues[0].value = (char *)calloc(size+1, sizeof(char));
        if (NULL == migrateRequest.keyvalues[0].value) {
            fprintf(stderr, "calloc(%d) failed due to %m.\n", size);
            exit(4);
        }

        int i;
        for (i = 0; i < numJobIds; i++) {
            if (0 == i) {
                snprintf(migrateRequest.keyvalues[0].value, size, "%lld", jobIds[i]);
                continue;
            }

            unsigned int lenValue;
            lenValue = strlen(migrateRequest.keyvalues[0].value);
            snprintf(migrateRequest.keyvalues[0].value+lenValue, size, " %lld", jobIds[i]);
        }

        if (NULL != strSpecNode && '\0') {
            migrateRequest.number ++;

            migrateRequest.keyvalues[1].key = REQUEST_KEY_NAMES;
            migrateRequest.keyvalues[1].value = copy_string(strSpecNode);
        }

        FREEUP(jobIds);
    } else {
        unsigned int num = 0; // user

        if (NULL != strUser) {
            num ++;
        }

        if (NULL != strJobName) {
            num ++;
        }

        if (0 == num) {
            fprintf(stderr, "Job ID or one of '-u/--user' and '-J/--jobname' must be specified.\n");
            migratejob_usage(argv[0]);
            exit(1);
        }

        if (NULL == strUser) { //If not specify -u, use my name.
            num ++;
        }

        if (NULL != strSpecNode) {
            num ++;
        }

        migrateRequest.number = num;
        migrateRequest.keyvalues = (struct keyvalue *)calloc(num, sizeof(struct keyvalue));
        if (NULL == migrateRequest.keyvalues) {
            fprintf(stderr, "calloc(%ld) failed due to %m.\n",
                    migrateRequest.number*sizeof(struct keyvalue));
            exit(4);
        }

        num = 0;
        migrateRequest.keyvalues[num].key = REQUEST_KEY_USERNAME;
        if (NULL == strUser) {
            migrateRequest.keyvalues[num].value = getmy_uname();
        } else {
            migrateRequest.keyvalues[num].value = copy_string(strUser);
        }
        num ++;

        if (NULL != strJobName) {
            migrateRequest.keyvalues[num].key = REQUEST_KEY_JOBNAME;
            migrateRequest.keyvalues[num].value = copy_string(strJobName);
            num ++;
        }

        if (NULL != strSpecNode && '\0') {

            migrateRequest.keyvalues[num].key = REQUEST_KEY_NAMES;
            migrateRequest.keyvalues[num].value = copy_string(strSpecNode);
            num ++;
        }
    }

    struct QuickPoolJobReply *jobReply;
    jobReply = client_migratejob(&migrateRequest, NULL);
    if (NULL == jobReply) {

        gf_xdr_free(gf_xdr_request, &migrateRequest);
        fprintf(stderr, "Faild to migrate job due to above reason.\n");

        exit(3);
    }

    gf_xdr_free(gf_xdr_request, &migrateRequest);

    unsigned int i;
    for (i = 0; i < jobReply->num_job; i++) {
        char strJobId[32];

        fprintf(stdout, "Job <%s> is migrated.\n",
                jobid_2string(jobReply->jobIDs[i], strJobId));
    }

    for (i = 0; i < jobReply->num_error; i++) {
        fprintf(stderr, "%s\n", jobReply->error_messages[i]);
    }

    if (0 < jobReply->num_error) {
        gf_xdr_free(libxdr_job_reply, jobReply);
        FREEUP(jobReply);
        exit(3);
    }

    gf_xdr_free(libxdr_job_reply, jobReply);
    FREEUP(jobReply);

    exit(0);
} // end function cmd_migrate_job

static void
migratejob_usage(const char *cmd)
{
    fprintf(stdout, "qp job %s usage: [-h, --help]", cmd);
    fprintf(stdout, " [-m, --node \"host_name ...\"] [-u, --user all|user_name]\n");
    fprintf(stdout, "\t\t  [-J, --jobname job_name] [jobId | \"jobId[index_list]\" ...]\n");

    return;
}
